﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization;


namespace KeanuMvc.Reference {

    public class XMLMediaTypeFormatter : MediaTypeFormatter {

        private static readonly MediaTypeHeaderValue xmlMediaType = new MediaTypeHeaderValue("application/xml");

        public XMLMediaTypeFormatter() {
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
            this.MediaTypeMappings.Add(new QueryStringMapping("format", "xml", xmlMediaType));
        }

        protected override object OnReadFromStream(Type type, System.IO.Stream stream, HttpContentHeaders contentHeaders) {
            var serializer = new XmlSerializer(type);
            return serializer.Deserialize(stream);
        }

        protected override void OnWriteToStream(Type type, object value, System.IO.Stream stream, HttpContentHeaders contentHeaders, System.Net.TransportContext context) {
            DataContractSerializer serializer = new DataContractSerializer(type);
            serializer.WriteObject(stream, value);
            //if (contentHeaders.ContentType.MediaType.Equals("application/xml", StringComparison.InvariantCultureIgnoreCase)) {
            //    if (!type.IsSimpleType()) {
            //        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            //        Byte[] bytes = encoding.GetBytes(value.ToXml().ToString());
            //        stream.Write(bytes, 0, bytes.Length);
            //    }
            //} 
            
        }
    }
}